﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLL.ComplexClasses;
using DAL;
using App_Log;
using App_Utils;
namespace BLL
{
    public class BL_Images
    {
        public static Image SaveRecord(Image objImage)
        {
            try
            {
                clsLog.logMsg("Image", "SaveRecord", "Started");
                DAL.ithubEntities db = new ithubEntities();
                var query = (from q in db.tblImages where q.img_id == objImage.img_id select q).SingleOrDefault();

                if (query != null)
                {
                    query = (tblImage)clsUtils.ConvertToObject(objImage, new tblImage());
                    db.SaveChanges();
                }
                else
                {
                    if (objImage.is_default == true)
                    {
                        db.tblImages.Where(m => m.is_default == true).ToList().ForEach(m => m.is_default = false);
                    }

                    tblImage _objtblImage = new tblImage();
                    _objtblImage = (tblImage)clsUtils.ConvertToObject(objImage, new tblImage());
                    db.tblImages.Add(_objtblImage);
                    db.SaveChanges();
                    objImage = (Image)clsUtils.ConvertToObject(_objtblImage, objImage);
                }
            }
            catch (Exception ex)
            {
                clsLog.logError("Image", "SaveRecord", ex.Message);
            }
            return objImage;
        }

        public static Image GetImagebyIDAndModule(long id, string module,bool? is_default = null)
        {
            Image objImage = new Image();

            try
            {
                clsLog.logMsg("Image", "GetImagebyIDAndModule", "Started");

                DAL.ithubEntities db = new ithubEntities();
                tblImage query = null;
                if (is_default != null)
                {
                    query = (from q in db.tblImages where q.id == id && q.module == module && q.is_visible == true && q.is_default == (bool)is_default select q).FirstOrDefault();
                }
                else
                {
                    query = (from q in db.tblImages where q.id == id && q.module == module && q.is_visible == true select q).FirstOrDefault();
                }

                

                if (query != null)
                {
                    objImage = (Image)App_Utils.clsUtils.ConvertToObject(query, new Image());
                }
                else
                {
                    objImage = null;
                }
            }
            catch (Exception ex)
            {
                clsLog.logError("Image", "GetImagebyIDAndModule", ex.Message);
            }
            return objImage;
        }



    }
}
